package com.runfast.waimai.util;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author chh
 */
public class HttpBase {

    private Logger log = null;    //日志显示
    private Map<String,String> fileMap = null;
    private Map<String,String> paramMap = null;
    private Map<String,String> handerMap = null;
    private Map<String,List<String>> cookieMap = null;
    private String postUrl = null;
    private String charset = null;
    private int responseCode = 0;
    private String responseText = null;
    private String requestText = null;//直接写入post的内容
    private boolean followRedirects = true;//是否302自动跳转

    public HttpBase(String postUrl){
        log = Logger.getLogger("HttpBase");
        fileMap = new HashMap<String,String>();
        paramMap = new HashMap<String,String>();
        handerMap = new HashMap<String,String>();
        cookieMap = new HashMap<String,List<String>>();
        this.postUrl = postUrl;
        this.charset = "UTF-8";
    }

    public void addFile(String key,String fileName){
        fileMap.put(key, fileName);
    }

    public void addParam(String key,String value){
        paramMap.put(key, value);
    }
    
    public void addHander(String key,String value){
    	handerMap.put(key, value);
    }
    
    public void clearHander(){
    	handerMap.clear();
    }

    public void clearParam(){
        paramMap.clear();
    }
    
    public Map<String,String> getParamMap(){
    	
    	return paramMap;
    }

    public void clearFile(){
        fileMap.clear();
    }
    
    public void setFollowRedirects(boolean followRedirects){
    	this.followRedirects = followRedirects;
    }

    public void reset(){
    	clearHander();
        clearParam();
        clearFile();
    }
    
    public Map<String,List<String>> getCookies(){
        return cookieMap;
    }

    public List<String> getCookie(String key){
        List<String> values = null;
        if(cookieMap!=null){
            values = cookieMap.get(key);
        }
        return values;
    }
    
    public void setCookie(Map<String,List<String>> cookieMap){
    	this.cookieMap = cookieMap;
    }

    public void get(){
        try {
            responseCode = 0;
            responseText = null;

            StringBuffer sbuf = new StringBuffer(postUrl);
            if(paramMap.size()>0){
                sbuf.append("?");
                Set<String> set = paramMap.keySet();
                Iterator<String> it = set.iterator();
                String key = null;
                String value = null;
                int count = 1;
                while(it.hasNext()){
                    key = it.next();
                    value = paramMap.get(key);
                    if(key!=null && value!=null){
                        sbuf.append(key).append("=").append(value);
                        if(count<set.size()){
                            sbuf.append("&");
                        }
                        count ++;
                    }
                }
            }

            URL url = new URL(sbuf.toString());
            //分隔标记符号
            HttpURLConnection.setFollowRedirects(followRedirects);
            HttpURLConnection httpConn = null;
            if(url.getProtocol().toUpperCase().equals("HTTP")){
            	httpConn = (HttpURLConnection) url.openConnection();
            }else{
            	httpConn = (HttpsURLConnection) url.openConnection();
            }            
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Accept-Language","zh-cn");
            httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729)");
            //httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
            httpConn.setRequestProperty("Host", url.getHost());
            httpConn.setRequestProperty("Pragma","no-cache");
            if(handerMap.size()>0){
            	Iterator<String> it = handerMap.keySet().iterator();
            	while(it.hasNext()){
            		String key = it.next();
            		String value = handerMap.get(key);
            		httpConn.setRequestProperty(key, value);
            	}
            }
            //System.out.println(url.getPort());
            
            ///////////////////////设置cookie///////////////////////////////
            if(cookieMap!=null && cookieMap.size()>0){
            	Iterator<String> it = cookieMap.keySet().iterator();
            	String key = null;
            	sbuf = new StringBuffer();
            	while(it.hasNext()){
            		key = it.next();
            		sbuf.append(key).append("=").append(cookieMap.get(key).get(0)).append(";");
            	}
            	//删掉最后一个分号
            	if(sbuf.length()>0){
            		sbuf.deleteCharAt(sbuf.length()-1);
            	}
            	httpConn.addRequestProperty("Cookie", sbuf.toString());
            }
            ////////////////////////////////////////////////////////////////

            httpConn.setRequestMethod("GET");
//            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            //流写入表单数据

            responseCode = httpConn.getResponseCode();
            BufferedReader br = null;
            if(responseCode==200){
                br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),getCharset()));
            }else if(responseCode!=302 && responseCode!=-1){
                br = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(),getCharset()));
            }
            if(br!=null){
                sbuf = new StringBuffer();
                String tmp = br.readLine();
                while (tmp != null) {
                    sbuf.append(tmp);
                    sbuf.append("\n");
                    tmp = br.readLine();
                }
                responseText = sbuf.toString();
            }
            
            /* 读取cookie */
            Map<String,List<String>> headers = httpConn.getHeaderFields();
            Iterator<String> it = headers.keySet().iterator();
            String location = null;
            while(it.hasNext()){
            	String key = it.next();
            	if(key!=null && key.toLowerCase(Locale.CHINA).equals("set-cookie")){
                    List<String> cookieList = headers.get(key);
                    if(cookieList!=null && cookieList.size()>0){
                        for(String cookie:cookieList){
                            if(cookie!=null && cookie.length()>0){
                                String args[] = cookie.split(";");
                                if(args!=null){
                                    for(String arg:args){
                                        if(arg!=null && arg.length()>0){
                                            String cookies[] = arg.split("=");
                                            if(cookies!=null && cookies.length==2){
                                                List<String> values = cookieMap.get(cookies[0]);
                                                if(values==null){
                                                    values = new ArrayList<String>();
                                                }
                                                if(values.size()==0){
                                                	values.add(cookies[1]);
                                                }else{
                                                	boolean isAdd = false;
                                                	for(String v:values){//不存在的才set进去
                                                		if(v.equals(cookies[1])){
                                                			isAdd = true;
                                                			break;
                                                		}
                                                	}
                                                	if(!isAdd){
                                                		values.add(cookies[1]);
                                                	}
                                                }
                                                //Log.d("ucapp", cookies[0]+"="+cookies[1]);
                                                cookieMap.put(cookies[0],values);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
            	}else if(key!=null && key.toLowerCase().equals("location")){
            		List<String> ls = headers.get(key);
            		if(ls!=null && ls.size()>0){
            			location = ls.get(0);
            		}
            	}
            }
            
            httpConn.disconnect();
            
            if(location!=null){//有重定向
            	postUrl = location;
            	reset();
            	get();
            	
            }
        } catch (MalformedURLException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void post(){
    	
        try {
            responseCode = 0;
            responseText = null;
            if(requestText!=null && requestText.length()>0){
                StringBuffer sbuf = new StringBuffer(postUrl);
                if(paramMap.size()>0){
                    sbuf.append("?");
                    Set<String> set = paramMap.keySet();
                    Iterator<String> it = set.iterator();
                    String key = null;
                    String value = null;
                    int count = 1;
                    while(it.hasNext()){
                        key = it.next();
                        value = paramMap.get(key);
                        if(key!=null && value!=null){
                            sbuf.append(key).append("=").append(value);
                            if(count<set.size()){
                                sbuf.append("&");
                            }
                            count ++;
                        }
                    }
                }
                postUrl = sbuf.toString();
            }
            URL url = new URL(postUrl);
            //分隔标记符号
            HttpURLConnection httpConn = null;
            if(url.getProtocol().toUpperCase().equals("HTTP")){
            	httpConn = (HttpURLConnection) url.openConnection();
            }else{
            	httpConn = (HttpsURLConnection) url.openConnection();
            }
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Accept-Language","zh-cn");
            httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729)");
            //httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
            httpConn.setRequestProperty("Host", url.getHost());
            httpConn.setRequestProperty("Pragma","no-cache");
            if(handerMap.size()>0){
            	Iterator<String> it = handerMap.keySet().iterator();
            	while(it.hasNext()){
            		String key = it.next();
            		String value = handerMap.get(key);
            		httpConn.setRequestProperty(key, value);
            	}
            }
            //System.out.println(url.getPort());
            
            ///////////////////////设置cookie///////////////////////////////
            if(cookieMap!=null && cookieMap.size()>0){
            	Iterator<String> it = cookieMap.keySet().iterator();
            	String key = null;
            	StringBuffer sbuf = new StringBuffer();
            	while(it.hasNext()){
            		key = it.next();
            		sbuf.append(key).append("=").append(cookieMap.get(key).get(0)).append(";");
            	}
            	//删掉最后一个分号
            	if(sbuf.length()>0){
            		sbuf.deleteCharAt(sbuf.length()-1);
            	}
            	httpConn.addRequestProperty("Cookie", sbuf.toString());
            }
            ////////////////////////////////////////////////////////////////

            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            //流写入表单数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(httpConn.getOutputStream(),getCharset()));

            if(requestText!=null && requestText.length()>0){
            	//有写入内容的情况,不设置value的格式
            	bw.write(requestText);
            }else{
                //先写入表单参数
                Set<String> set = paramMap.keySet();
                Iterator<String> it = set.iterator();
                String key = null;
                String value = null;
                int count = 1;
                while(it.hasNext()){
                    key = it.next();
                    value = paramMap.get(key);
                    if(key!=null && value!=null){
                        bw.write(key);
                        bw.write("=");
                        bw.write(value);
                        if(count<set.size()){
                            bw.write("&");
                        }
                        count ++;
                    }
                }
            }
            bw.flush();
            bw.close();

            responseCode = httpConn.getResponseCode();
            BufferedReader br = null;
            if(responseCode==200){
                br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),getCharset()));
            }else{
                br = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(),getCharset()));
            }
            StringBuffer sbuf = new StringBuffer();
            String tmp = br.readLine();
            while (tmp != null) {
                sbuf.append(tmp);
                tmp = br.readLine();
            }
            responseText = sbuf.toString();
            
            /* 读取cookie */
            Map<String,List<String>> headers = httpConn.getHeaderFields();
            Iterator<String> it = headers.keySet().iterator();
            while(it.hasNext()){
            	String key = it.next();
            	if(key!=null && key.toLowerCase(Locale.CHINA).equals("set-cookie")){
                    List<String> cookieList = headers.get(key);
                    if(cookieList!=null && cookieList.size()>0){
                        for(String cookie:cookieList){
                            if(cookie!=null && cookie.length()>0){
                                String args[] = cookie.split(";");
                                if(args!=null){
                                    for(String arg:args){
                                        if(arg!=null && arg.length()>0){
                                        	int index = arg.indexOf("=");
                                        	if(index!=-1){
                                        		String cookies[] = new String[2];
                                        		cookies[0] = arg.substring(0, index);
                                        		cookies[1] = arg.substring(index+1);
                                                List<String> values = cookieMap.get(cookies[0]);
                                                if(values==null){
                                                    values = new ArrayList<String>();
                                                }
                                                values.add(cookies[1]);
                                                //Log.d("ucapp", cookies[0]+"="+cookies[1]);
                                                cookieMap.put(cookies[0],values);
                                        	}
//                                            String cookies[] = arg.split("=");
//                                            if(cookies!=null && cookies.length==2){
//                                                List<String> values = cookieMap.get(cookies[0]);
//                                                if(values==null){
//                                                    values = new ArrayList<String>();
//                                                }
//                                                values.add(cookies[1]);
//                                                //Log.d("ucapp", cookies[0]+"="+cookies[1]);
//                                                cookieMap.put(cookies[0],values);
//                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
            	}
            }
            
            httpConn.disconnect();
        } catch (MalformedURLException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void upload(){
        try {
            responseCode = 0;
            responseText = null;
            URL url = new URL(postUrl);
            //分隔标记符号
            String boundary = "---------------------------7da2a82d1806d6";
            HttpURLConnection httpConn = null;
            if(url.getProtocol().toUpperCase().equals("HTTP")){
            	httpConn = (HttpURLConnection) url.openConnection();
            }else{
            	httpConn = (HttpsURLConnection) url.openConnection();
            }
            httpConn.setRequestProperty("Accept", " image/gif, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
            httpConn.setRequestProperty("Accept-Language","zh-cn");
            httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729)");
            httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
            httpConn.setRequestProperty("Host", url.getHost());
            httpConn.setRequestProperty("Pragma","no-cache");
            if(handerMap.size()>0){
            	Iterator<String> it = handerMap.keySet().iterator();
            	while(it.hasNext()){
            		String key = it.next();
            		String value = handerMap.get(key);
            		httpConn.setRequestProperty(key, value);
            	}
            }
            //System.out.println(url.getPort());
            ///////////////////////设置cookie///////////////////////////////
            if(cookieMap!=null && cookieMap.size()>0){
            	Iterator<String> it = cookieMap.keySet().iterator();
            	String key = null;
            	StringBuffer sbuf = new StringBuffer();
            	while(it.hasNext()){
            		key = it.next();
            		sbuf.append(key).append("=").append(cookieMap.get(key).get(0)).append(";");
            	}
            	//删掉最后一个分号
            	if(sbuf.length()>0){
            		sbuf.deleteCharAt(sbuf.length()-1);
            	}
            	httpConn.addRequestProperty("Cookie", sbuf.toString());
            }
            ////////////////////////////////////////////////////////////////

            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            //生成一个临时流写入表单数据
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(baos,getCharset()));
            //因为写文件要用字节流，所以要使用bos
            BufferedOutputStream bos = new BufferedOutputStream(httpConn.getOutputStream());

            //先写入表单参数
            Iterator<String> it = paramMap.keySet().iterator();
            String key = null;
            String value = null;
            while(it.hasNext()){
                key = it.next();
                value = paramMap.get(key);
                if(key!=null && value!=null){
                    //要在分隔标志符号前加--以及后面加\r\n
                    bw.write("--"+boundary+"\r\n");
                    bw.write("Content-Disposition: form-data; name=\""+key+"\"\r\n\r\n");
                    bw.write(value);
                    bw.write("\r\n");
                }
            }
            bw.flush();
            bos.write(baos.toByteArray());

            //写入文件
            byte[] buf = new byte[2048];//读入流缓存
            int len = 0;
            //int fileCount = 1;
            it = fileMap.keySet().iterator();
            String fileName = null;
            while(it.hasNext()){
                key = it.next();
                value = fileMap.get(key);
                try{
                    File file = new File(value);
                    if(file.exists() && file.isFile()){
                        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                        len = bis.read(buf);
                        fileName = file.getName();
                        baos.reset();
                        //要在分隔标志符号前加--以及后面加\r\n
                        bw.write("--"+boundary+"\r\n");
                        bw.write("Content-Disposition: form-data; name=\""+key+"\"; filename=\""+fileName+"\"; filelength=\""+file.length()+"\"\r\n");
                        bw.write("Content-Type: ");
                        if(fileName.toLowerCase().endsWith(".jpg")){
                            bw.write("image/jpeg\r\n\r\n");
                        }else{
                            bw.write("image/gif\r\n\r\n");
                        }
                        bw.flush();
                        bos.write(baos.toByteArray());
                        while(len>0){
                            bos.write(buf, 0, len);
                            len = bis.read(buf);
                        }
                        bis.close();
                        bos.write(13);//r
                        bos.write(10);//n
                    }else{
                        log.info("无法读取："+value);
                    }
                }catch(IOException ie){
                    Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ie);
                }
                //fileCount ++;
            }
            baos.reset();
            //结束要在分隔标志符号前加--以及后面加--,还需要加上\r\n,否则微信服务器不认
            bw.write("--"+boundary+"--\r\n");
            bw.flush();
            bos.write(baos.toByteArray());
            bos.flush();
            bos.close();
            //提交数据完成

            responseCode = httpConn.getResponseCode();
            BufferedReader br = null;
            if(responseCode==200){
                br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),getCharset()));
            }else{
                br = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(),getCharset()));
            }
            StringBuffer sbuf = new StringBuffer();
            String tmp = br.readLine();
            while (tmp != null) {
                sbuf.append(tmp);
                tmp = br.readLine();
            }
            responseText = sbuf.toString();

            httpConn.disconnect();
        } catch (MalformedURLException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public String downFile(String savePath){

    	String fileName = null;
        try {
            responseCode = 0;
            responseText = null;

            StringBuffer sbuf = new StringBuffer(postUrl);
            if(paramMap.size()>0){
                sbuf.append("?");
                Set<String> set = paramMap.keySet();
                Iterator<String> it = set.iterator();
                String key = null;
                String value = null;
                int count = 1;
                while(it.hasNext()){
                    key = it.next();
                    value = paramMap.get(key);
                    if(key!=null && value!=null){
                        sbuf.append(key).append("=").append(value);
                        if(count<set.size()){
                            sbuf.append("&");
                        }
                        count ++;
                    }
                }
            }

            URL url = new URL(sbuf.toString());
            //分隔标记符号
            HttpURLConnection httpConn = null;
            if(url.getProtocol().toUpperCase().equals("HTTP")){
            	httpConn = (HttpURLConnection) url.openConnection();
            }else{
            	httpConn = (HttpsURLConnection) url.openConnection();
            }
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Accept-Language","zh-cn");
            httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729)");
            httpConn.setRequestProperty("Host", url.getHost());
            httpConn.setRequestProperty("Pragma","no-cache");
            if(handerMap.size()>0){
            	Iterator<String> it = handerMap.keySet().iterator();
            	while(it.hasNext()){
            		String key = it.next();
            		String value = handerMap.get(key);
            		httpConn.setRequestProperty(key, value);
            	}
            }
            
            ///////////////////////设置cookie///////////////////////////////
            if(cookieMap!=null && cookieMap.size()>0){
            	Iterator<String> it = cookieMap.keySet().iterator();
            	String key = null;
            	sbuf = new StringBuffer();
            	while(it.hasNext()){
            		key = it.next();
            		sbuf.append(key).append("=").append(cookieMap.get(key).get(0)).append(";");
            	}
            	//删掉最后一个分号
            	if(sbuf.length()>0){
            		sbuf.deleteCharAt(sbuf.length()-1);
            	}
            	httpConn.addRequestProperty("Cookie", sbuf.toString());
            }
            ////////////////////////////////////////////////////////////////

            httpConn.setRequestMethod("GET");
//            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            //流写入表单数据

            responseCode = httpConn.getResponseCode();

            BufferedInputStream bis = null;
            if(responseCode==200){
            	if(!savePath.endsWith(File.separator)){
            		savePath += File.separator;
            	}
            	
            	String fileInfo = httpConn.getHeaderField("Content-disposition");
            	System.out.println("fileInfo="+fileInfo);
            	int startIdx = fileInfo.indexOf("filename=\"");
            	System.out.println("startIdx:"+startIdx);
            	if(startIdx!=-1){
            		int endIdx = fileInfo.indexOf("\"",startIdx+10);
            		System.out.println("endIdx:"+endIdx);
            		if(endIdx>startIdx){
            			fileName = fileInfo.substring(startIdx+10, endIdx);
            		}
            	}else{
            		fileName = Long.toString(System.currentTimeMillis());
            	}
                bis = new BufferedInputStream(httpConn.getInputStream());
            }
            byte[] buf = new byte[4096];
            int len = bis.read(buf);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savePath + fileName));
            while(len>0){
                bos.write(buf, 0, len);
                len = bis.read(buf);
            }
            bis.close();
            bos.flush();
            bos.close();
            
            httpConn.disconnect();
        } catch (MalformedURLException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        }

        return fileName;
    }    

    public byte[] getFile(){

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();

        try {
            responseCode = 0;
            responseText = null;

            StringBuffer sbuf = new StringBuffer(postUrl);
            if(paramMap.size()>0){
                sbuf.append("?");
                Set<String> set = paramMap.keySet();
                Iterator<String> it = set.iterator();
                String key = null;
                String value = null;
                int count = 1;
                while(it.hasNext()){
                    key = it.next();
                    value = paramMap.get(key);
                    if(key!=null && value!=null){
                        sbuf.append(key).append("=").append(value);
                        if(count<set.size()){
                            sbuf.append("&");
                        }
                        count ++;
                    }
                }
            }

            URL url = new URL(sbuf.toString());
            //分隔标记符号
            HttpURLConnection httpConn = null;
            if(url.getProtocol().toUpperCase().equals("HTTP")){
            	httpConn = (HttpURLConnection) url.openConnection();
            }else{
            	httpConn = (HttpsURLConnection) url.openConnection();
            }
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Accept-Language","zh-cn");
            httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729)");
            httpConn.setRequestProperty("Host", url.getHost());
            httpConn.setRequestProperty("Pragma","no-cache");
            if(handerMap.size()>0){
            	Iterator<String> it = handerMap.keySet().iterator();
            	while(it.hasNext()){
            		String key = it.next();
            		String value = handerMap.get(key);
            		httpConn.setRequestProperty(key, value);
            	}
            }
            
            ///////////////////////设置cookie///////////////////////////////
            if(cookieMap!=null && cookieMap.size()>0){
            	Iterator<String> it = cookieMap.keySet().iterator();
            	String key = null;
            	sbuf = new StringBuffer();
            	while(it.hasNext()){
            		key = it.next();
            		sbuf.append(key).append("=").append(cookieMap.get(key).get(0)).append(";");
            	}
            	//删掉最后一个分号
            	if(sbuf.length()>0){
            		sbuf.deleteCharAt(sbuf.length()-1);
            	}
            	httpConn.addRequestProperty("Cookie", sbuf.toString());
            }
            ////////////////////////////////////////////////////////////////

            httpConn.setRequestMethod("GET");
//            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            //流写入表单数据

            responseCode = httpConn.getResponseCode();

            BufferedInputStream bis = null;
            if(responseCode==200){
                bis = new BufferedInputStream(httpConn.getInputStream());
            }
            byte[] buf = new byte[4096];
            int len = bis.read(buf);
            while(len>0){
                byteOut.write(buf, 0, len);
                len = bis.read(buf);
            }
            bis.close();
            
            httpConn.disconnect();
        } catch (MalformedURLException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
        }

        return byteOut.toByteArray();
    }

    /**
     * @return the responseCode
     */
    public int getResponseCode() {
        return responseCode;
    }

    /**
     * @param responseCode the responseCode to set
     */
    public void setResponseCode(int responseCode) {
        this.responseCode = responseCode;
    }

    /**
     * @return the responseText
     */
    public String getResponseText() {
        return responseText;
    }

    /**
     * @param responseText the responseText to set
     */
    public void setResponseText(String responseText) {
        this.responseText = responseText;
    }

    public String getRequestText() {
		return requestText;
	}

	public void setRequestText(String requestText) {
		this.requestText = requestText;
	}

	/**
     * @return the charset
     */
    public String getCharset() {
        return charset;
    }

    /**
     * @param charset the charset to set
     */
    public void setCharset(String charset) {
        this.charset = charset;
    }

    public void saveFile(byte[] buf,String fileName){
        if(buf!=null && buf.length>0 && fileName!=null && fileName.length()>0){
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
                bos.write(buf);
                bos.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String args[]){
//        Properties prop = System.getProperties();
//        //设置http访问要使用的代理服务器的地址
//        prop.setProperty("http.proxyHost", "127.0.0.1");
//        //设置http访问要使用的代理服务器的端口
//        prop.setProperty("http.proxyPort", "8900");
        //http://192.168.1.122:8084/jttz/servlet/UpLoadFileServlet
//        HttpBase httpUpload = new HttpBase("http://chy305.aliapp.com/api/E1415265451356057.do?signature=566A76D344A65614FC875A75976E18FED533638D&timestamp=1111&nonce=1111");
//        httpUpload.setCharset("UTF-8");
//        httpUpload.addHander("Content-Type", "text/plain");
//        //httpUpload.setRequestText(" <xml>\n <ToUserName><![CDATA[toUser]]></ToUserName>\n <FromUserName><![CDATA[fromUser]]></FromUserName> \n <CreateTime>1348831860</CreateTime>\n <MsgType><![CDATA[text]]></MsgType>\n <Content><![CDATA[南宁到北京航班]]></Content>\n <MsgId>1234567890123456</MsgId>\n </xml>");
//        httpUpload.setRequestText("<xml>\n<ToUserName><![CDATA[chy305]]></ToUserName>\n<FromUserName><![CDATA[odkICtxJ6XRAiz1qObsXp7j172QE]]></FromUserName>\n<CreateTime>123456789</CreateTime>\n<MsgType><![CDATA[event]]></MsgType>\n<Event><![CDATA[subscribe]]></Event>\n</xml>");
//        httpUpload.post();
//        byte[] buf = httpUpload.getFile();
//        try {
//            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:\\142905.jpg"));
//            bos.write(buf);
//            bos.close();
//        httpUpload.addFile("file1","e:\\pp.jpg");
//        httpUpload.addFile("file1","d:\\ccc.jpg");
//        httpUpload.addParam("inp", "titleImg");
//        httpUpload.upload();
//        } catch (FileNotFoundException ex) {
//            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(HttpBase.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        httpUpload.addFile("file1","e:\\pp.jpg");
//        httpUpload.addFile("file1","d:\\ccc.jpg");
//        httpUpload.addParam("inp", "titleImg");
//        httpUpload.upload();
//
//        System.out.println(httpUpload.getResponseCode());
//        System.out.println(httpUpload.getResponseText());
//    	String result = WXApi.uploadMediaFile("qhn6k5GGfSLs_OnH52cIzOhcnDq5M1Ax4nvBk_ZRr61GaY0pHRlNqBVhHizIuqyU6K0MVzwUP7JSZSwabyeVQw", 
//    			"image", "G:\\photo\\haha.jpg");
//    	System.out.println(result);
    }
}
